<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function gift_add_page() {
    return drupal_get_form('gift_edit_form');
}

function gift_edit_page($id) {
    return drupal_get_form('gift_edit_form', $id);
}

function gift_edit_form($form, &$form_state) {
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }

    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('gift', 'gift_id', $id);
        if (empty($record)) {
            drupal_set_message(t('礼物信息不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#gift_id'] = $id;
    }
    global $user;
    // 判断用户角色
    if(!nonghua_user_access_with_double_permissions('gift', 'view', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    if (get_user_role_name($user->uid) === '农户') {
        $form['farmer_id'] = array(
            '#type' => 'hidden',
            '#value' => $user->uid,
        );
    } else {//农化服务人员
        _insert_farmer_select_info($form,$form_state,$record);
    }

    $form['gift']['gift_type'] = array(
        '#type' => 'select',
        '#title' => '礼物类型',
        '#options' => array(
            0 => '礼物类型',
            1 => '化肥',
            2 => '代金券',
        ),
        '#default_value' => !empty($record) ? $record->gift_type : 0,
        '#required' => TRUE,
    );
    $form['gift']['quantity'] = array(
        '#type' => 'textfield',
        '#title' => '赠送数量',
        '#default_value' => !empty($record) ? $record->quantity : '',
        '#required' => TRUE,
    );

    $form['gift']['comments'] = array(
        '#type' => 'textarea',
        '#title' => '赠送备注',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#required' => FALSE,
        '#maxlength' =>50,
    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($record) ? '修改' : '添加',
        '#access' => nonghua_user_access_with_double_permissions('gift', 'manage', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0),
    );
    return $form;
}

function gift_edit_form_validate($form, &$form_state) {
    if(!empty($form_state['values']['quantity'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['quantity']) || (strlen(explode('.',$form_state['values']['quantity'])[0])>8)) {
            form_set_error('area', "赠送数量格式错误");
        }
    }
    if (empty($form_state['values']['farmer_id'])) {
        form_set_error('farmer_name', '必须选择 农户');
    }
    if(empty($form_state['values']['gift_type'])){
        form_set_error('gift_type', '必须选择礼物类型');
    }
}

function gift_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (empty($id)) { //add new gift
        $nid = db_insert('gift') // Table name no longer needs {}
                ->fields(array(
                    'farmer_id' =>  $form_state['values']['farmer_id'],
                    'gift_type' => $form_state['values']['gift_type'],
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'quantity' => $form_state['values']['quantity'],
                    'comments' => $form_state['values']['comments'],
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
        if(!empty($_GET['farmer_id'])){
            drupal_goto('gift/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
        }
    } else {
        $nid = db_update('gift') // edit exsting store. todo: update only modified fields
                ->fields(array(
                    'farmer_id' =>  $form_state['values']['farmer_id'],
                    'gift_type' => $form_state['values']['gift_type'],
                    'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                    'quantity' => $form_state['values']['quantity'],
                    'comments' => $form_state['values']['comments'],
                    'timestamp' => time(),))
                ->condition('gift_id',$id,'=')
                ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['farmer_id'])){
            drupal_goto('gift/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
        }
    }
}

function gift_assign_submit(){
    if(isset($_POST['ids'])){
        $ids = $_POST['ids'];
        unset($_POST['ids']);
    }
    if(isset($_POST['gift_type'])){
        $gift_type =$_POST['gift_type'];
    }
    if(isset($_POST['quantity'])){
        $quantity =$_POST['quantity'];
    }
    if(isset($_POST['comments'])){
        $comments =$_POST['comments'];
    }
    $transaction = db_transaction();//数据库事务

    global $user;
    try{
        if (!empty($ids)) {
            foreach ($ids  as  $farmer_id) {
                $nid = db_insert('gift')// Table name no longer needs {}
                ->fields(array(
                    'farmer_id' =>  $farmer_id,
                    'gift_type' => $gift_type,
                    'quantity' => $quantity,
                    'comments' => $comments,
                    'author_uid' => $user->uid,
                    'timestamp' => time(),))
                    ->execute();
            }
        }
        $result = array ('success'=>0,'errorNum'=>0);
        echo json_encode($result);

    }catch (Exception $e) {
        $transaction->rollback();
        $result = array ('success'=>1,'errorNum'=>0);
        echo json_encode($result);
    }

}
